package com.estronger.shopmanage.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.BeanImage;
import com.estronger.shopmanage.utils.FileUtils;
import com.estronger.shopmanage.utils.ImageUtil;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.SDCardUtil;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.adapter.PhotoRecyclerAdapter;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.soonfor.evaluate.activity.ShowPicActivity;
import com.tbruyelle.rxpermissions2.Permission;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.jesse.nativelogger.NLogger;

/**
 * 增加图片
 */
public class AddPhotosView extends LinearLayout {

    public interface AddMediaListenner{
        void onDelete(AddPhotosView view,LocalMedia media,int position);
    }

    private int _id = 0;//组件id，一个界面使用多次组件时用于区别的id
    private Activity mActivity;
    private TextView tv_photos_title;//标题
    private ImageView iv_open_album;//打开相册
    private ImageView iv_open_camera;//打开相机
    private LinearLayout ll_rvh_photos;//横向滚动的图片展示
    private RecyclerView rvh_photos;//横向滚动的图片展示
    private PhotoRecyclerAdapter prAdapter;//图片的适配器
    private EventListener listener;
    private int count = 10;//最大数量
    private Gson gson;

    private int uploadFileCount = 0;

    AddMediaListenner addMediaListenner;

    public void setAddMediaListenner(AddMediaListenner addMediaListenner) {
        this.addMediaListenner = addMediaListenner;
    }

    String cameraTempPath = null;

    public AddPhotosView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View view = View.inflate(context, R.layout.view_addphotos, this);
        findViewById(view);
    }

    private void findViewById(View view) {
        tv_photos_title = view.findViewById(R.id.tv_photos_title);
        iv_open_album = view.findViewById(R.id.iv_open_album);
        iv_open_camera = view.findViewById(R.id.iv_open_camera);
        ll_rvh_photos = view.findViewById(R.id.ll_rvh_photos);
        rvh_photos = view.findViewById(R.id.rvh_photos);
        iv_open_album.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                PermissionUtils.getInstance().requestPromisssions(mActivity, new PermissionUtils.AcceptListener() {
                            @Override
                            public void grante() {
                                if (listener != null) listener.openAlbum(_id);
                            }

                            @Override
                            public void denial(Permission permission) {
                                NLogger.e("您拒绝了读取存储权限，无法使用相册功能!");
                            }

                            @Override
                            public void fail() {

                            }
                        },
                        Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        });
        iv_open_camera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                PermissionUtils.getInstance().requestPromisssions(mActivity, new PermissionUtils.AcceptListener() {
                            @Override
                            public void grante() {
                                if (mActivity != null){
                                    if (listener != null) {
                                       boolean b = listener.openCamera(_id);
                                       if (b)return;
                                    }
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    if (cameraTempPath == null){
                                        String folder = SDCardUtil.SDCardRoot + "HomeCase";//临时存储路径
                                        File folderFile = new File(folder);
                                        if (!folderFile.exists()){
                                            folderFile.mkdirs();
                                        }
                                        cameraTempPath = folder  + "/take_photo_temp.jpg";
                                    }
                                    File file = new File(cameraTempPath);
                                    Uri imageUri = Uri.fromFile(file);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//Android7.0以上
                                        imageUri = FileProvider.getUriForFile(mActivity, "com.estronger.shopmanage.fileprovider", file);//通过FileProvider创建一个content类型的Uri
                                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    }
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                    int code =  _id + 2;
                                    mActivity.startActivityForResult(intent, code);
                                    return;
                                }
                            }

                            @Override
                            public void denial(Permission permission) {
                                NLogger.e("您拒绝了拍照权限，无法使用拍照功能!");
                            }

                            @Override
                            public void fail() {

                            }
                        },
                        Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        });
        ll_rvh_photos.setVisibility(GONE);
    }

    /*
    * 删除元素
    * */
    public void removeItem(int position){
        if (prAdapter.getMyList().size() > position && position >= 0){
            prAdapter.getMyList().remove(position);
            prAdapter.notifyDataSetChanged();
            updateView();
        }
    }

    /**
     * 初始化界面
     *
     * @param activity
     */
    public void initView(Activity activity, int id, final EventListener listener) {
        this.gson = new Gson();
        this.mActivity = activity;
        this._id = id;
        this.listener = listener;
        LinearLayoutManager photosManager = new LinearLayoutManager(mActivity);
        photosManager.setOrientation(LinearLayout.HORIZONTAL);
        rvh_photos.setLayoutManager(photosManager);
        prAdapter = new PhotoRecyclerAdapter(mActivity);
        prAdapter.setPhotosAdaterCallback(new PhotoRecyclerAdapter.PhotosAdaterCallback() {
            @Override
            public void preview(ArrayList<String> pics, int position) {
                ShowPicActivity.previewCanDelete(mActivity, pics, position, true, _id + 3, false);
            }

            @Override
            public void delete(int pos) {
                if (prAdapter.getMyList().size() > pos){
                    LocalMedia media = prAdapter.getMyList().get(pos);
                    if (media.getPath().startsWith("http://") || media.getPath().startsWith("https://")){
                        if (addMediaListenner != null){
                            addMediaListenner.onDelete(AddPhotosView.this,media,pos);
                        }
                    }else {
                        prAdapter.getMyList().remove(pos);
                        prAdapter.notifyDataSetChanged();
                        updateView();
                    }
                }
            }
        });
        rvh_photos.setAdapter(prAdapter);
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    /**
     * 初始化数据
     *
     * @param maxSize 图片显示的最大张数
     */
    public void initData(String title, int maxSize) {
        this.count = maxSize;
        tv_photos_title.setText(title);
        prAdapter.setMaxSize(maxSize);
    }

    /*设置显示的图片*/
    public void setImagesList(List<LocalMedia> arr){
        prAdapter.notifyDataSetChanged(arr,true);
        updateView();
    }

    public void updateView() {
        if (prAdapter.getItemCount() == 0) {
            ll_rvh_photos.setVisibility(GONE);
        } else {
            ll_rvh_photos.setVisibility(VISIBLE);
            if (prAdapter.getItemCount() > count) {
                Toast.show(mActivity, "最大可选择" + count + "张图片!", Toast.LENGTH_SHORT);
            }
        }
    }

//    //选择图片或拍照后后回调
    @SuppressLint("WrongThread")
    public void onActivityResult(int requestCode, Intent data) {
        if (data != null || requestCode == _id + 2) {//2022-08-05 拍照保存方式修改，为了获取到大图
            if (requestCode == _id + 1) {//选择图片
                //选择图片后的回调
                if (listener != null) {
                    listener.showLoadDialog();
                }
                List<LocalMedia> bitmapItems = PictureSelector.obtainMultipleResult(data);
                prAdapter.notifyDataSetChanged(bitmapItems, true);
                updateView();
                if (listener != null) {
                    listener.closeLoadDialog();
                }
            } else if (requestCode == _id + 2) {//拍照
                if (listener != null) {
                    listener.showLoadDialog();
                }
                if (TextUtils.isEmpty(cameraTempPath))return;
                Bitmap photo = BitmapFactory.decodeFile(cameraTempPath);

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String waterText = format.format(new Date());
                String location = TextUtils.isEmpty(MyApplication.address)?"":MyApplication.address;
                /*添加水印*/
                photo = ImageUtil.drawTextToLeftBottom(mActivity,photo,waterText,location,30, Color.WHITE,30,40);
                if (photo != null) {
                    String photoPath = mActivity.getFilesDir() + "/" + SystemClock.uptimeMillis() + ".jpg";
                    File file = new File(photoPath);
                    FileOutputStream fos;
                    try {
                        fos = new FileOutputStream(file);
                        photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        LocalMedia localMedia = new LocalMedia();
                        localMedia.setCompressPath(photoPath);
                        localMedia.setPath(photoPath);
                        prAdapter.notifyDataSetChanged(localMedia, false);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    updateView();
                }
                if (listener != null) {
                    listener.closeLoadDialog();
                }
            } else if (requestCode == ShowPicActivity.CODE_DELETE_FINISH) {
                //删除了图片后返回
                ArrayList<String> list = data.getStringArrayListExtra("delted_list");
                if (list != null && list.size() > 0) {
                    List<LocalMedia> adapterList = getFileList();
                    for (String url : list) {
                        for (int i = adapterList.size() - 1; i >= 0; i--) {
                            if (adapterList.get(i).getPath().equals(url) || adapterList.get(i).getCompressPath().equals(url)) {
                                adapterList.remove(i);
                            }
                        }
                    }
                    prAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    public int getPhotosCount() {
        if (prAdapter != null) return prAdapter.getItemCount();
        else return 0;
    }

    ;

    public List<LocalMedia> getFileList() {
        return prAdapter.getMyList();
    }

    /**
     * 计算结果个数
     */
    private int requestSuccessCount = 0;//成功
    private int requestFailCount = 0;//失败

    /**
     * 上传成功图片的图片
     */
    ArrayList<String> uploadImgUrls;

    /**
     * 上传图片
     */
    public void postPics() {
        requestSuccessCount = 0;
        requestFailCount = 0;
        if (uploadImgUrls == null) {
            uploadImgUrls = new ArrayList<>();
        } else if (uploadImgUrls.size() > 0) {
            uploadImgUrls.clear();
        }
        List<LocalMedia> localList = prAdapter.getMyList();
        if (localList != null && localList.size() > 0) {
            uploadFileCount = 0;
            //上传图片
            for (int i = 0; i < localList.size(); i++) {
                LocalMedia media = localList.get(i);
                //网络图片不再上传
                if (!media.getPath().startsWith("http://") && !media.getPath().startsWith("https://")){
                    String path = TextUtils.isEmpty(media.getAndroidQToPath())?media.getPath():media.getAndroidQToPath();
                    File file = new File(path);
                    RequestParams forIMG = new RequestParams();
                    forIMG.addBodyParameter("usercode", MyApplication.getUserCode());
                    forIMG.addBodyParameter("dir", "image");
                    forIMG.addBodyParameter("imgFile", file);
                    listener.uploadPic(forIMG, _id);
                    uploadFileCount ++;
                }
            }
            if (uploadFileCount == 0){//没有图片提交则结束
                listener.afterUploadPics(true, uploadImgUrls, _id);
            }
        } else {
            listener.afterUploadPics(true, uploadImgUrls, _id);
        }
    }

    //图片上传成功
    public void uploadSuccess(int code, String result) {
        BeanImage bean = gson.fromJson(result, BeanImage.class);
        // 进入activity时获取的同事信息
        if (bean.error == 0) {
            uploadImgUrls.add(bean.filepath);
        }
        saveData(true, code, "");
    }

    //图片上传失败
    public void uploadFail(int requestCode, String msg) {
        saveData(false, requestCode, msg);
    }

    public synchronized void saveData(boolean isSuccess, int requestCode, String msg) {
        if (isSuccess)
            requestSuccessCount++;
        else {
            requestFailCount++;
        }
        if (requestSuccessCount + requestFailCount == uploadFileCount) {
            if (requestFailCount > 0) {
                requestSuccessCount = 0;
                requestFailCount = 0;
                Toast.show(mActivity, "上传图片失败" + (TextUtils.isEmpty(msg) ? "" : ":" + msg), Toast.LENGTH_SHORT);
                listener.afterUploadPics(false, null, requestCode);
            } else {
                //如果全部请求都返回,则进行下一步，暂时不考虑个别失败的情况
                requestSuccessCount = 0;
                requestFailCount = 0;
                listener.afterUploadPics(true, uploadImgUrls, requestCode);
            }
        }
    }


    public interface EventListener {
        void openAlbum(int id);//打开相册进行选择图片

        boolean openCamera(int id);//打开相机拍照

        void uploadPic(RequestParams params, int requestCode);//上传图片

        void uploadVideoByParam(RequestParams params, int code);//上传视频

        void afterUploadVideos(boolean isSuccess, ArrayList<BeanImage> urls, int requestCode);//上传完图片后

        void afterUploadPics(boolean isSuccess, ArrayList<String> urls, int requestCode);//上传图片

        void showLoadDialog();

        void closeLoadDialog();
    }
}